#include "hyperspinmodel.h"

#include <QMetaType>
#include <QDir>

HyperspinModel::HyperspinModel(const QString &system, QObject *parent) :
  QAbstractItemModel(parent),
  _system(system)
{
  _entries = hs::entries(system);
  refreshFavorites();
}

QModelIndex HyperspinModel::index(int row, int column, const QModelIndex &parent) const
{
  if (parent.isValid() || row >= _entries.size() || column != 0)
    return QModelIndex();
  return createIndex(row,column);
}

QModelIndex HyperspinModel::parent(const QModelIndex &) const
{
  return QModelIndex();
}

int HyperspinModel::rowCount(const QModelIndex &parent) const
{
  if (parent.isValid())
    return 0;
  return _entries.size();
}

int HyperspinModel::columnCount(const QModelIndex &parent) const
{
  if (parent.isValid())
    return 0;
  return 1;
}

QVariant HyperspinModel::data(const QModelIndex &index, int role) const
{
  if (!index.isValid())
    return QVariant();

  if (role == Qt::DisplayRole || role == hs::DescriptionRole)
  {
    return _entries[index.row()].second;
  }
  else if (role == hs::NameRole)
  {
    return _entries[index.row()].first;
  }
  else if (role == hs::ArtRole)
  {
    return hs::art(_system,_entries[index.row()].first);
  }
  else if (role == hs::FavoriteRole)
  {
    return _favorites.contains(_entries[index.row()].first);
  }
  return QVariant();
}

QString HyperspinModel::system() const
{
  return _system;
}

void HyperspinModel::refreshFavorites()
{
  QFile favFile(QDir(hs::ROOT_FOLDER).absoluteFilePath(QString("Databases/%1/favorites.txt").arg(_system)));
  favFile.open(QIODevice::ReadOnly);
  QString line;
  while (!(line = QString(favFile.readLine()).remove("\r").remove("\n")).isEmpty())
  {
    _favorites.insert(line);
  }
}

int HyperspinModel::favoritesCount() const
{
  return _favorites.size();
}

void HyperspinModel::setSystem(const QString &system)
{
  beginResetModel();
  _system = system;
  _entries = hs::entries(system);
  endResetModel();
}

void HyperspinModel::setFavorite(const QString &name, bool fav)
{
  if (fav)
    _favorites.insert(name);
  else
    _favorites.remove(name);

  QFile favFile(QDir(hs::ROOT_FOLDER).absoluteFilePath(QString("Databases/%1/favorites.txt").arg(_system)));
  favFile.open(QIODevice::ReadWrite | QIODevice::Truncate);
  foreach(const QString& f, _favorites)
  {
    favFile.write(QString(f + "\r\n").toUtf8());
  }
  favFile.close();
}
